home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 14576 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.5 KB

  1. Path: crl.crl.com!not-for-mail
  2. From: bobfry@crl.com (Robert Fry)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: char* still alive after free ???
  5. Date: 15 Apr 1996 13:58:43 -0700
  6. Organization: CRL Dialup Internet Access
  7. Message-ID: <4kuda3$5vc@crl.crl.com>
  8. References: <317269EA.11BB93C2@studbox.uni-stuttgart.de>
  9. NNTP-Posting-Host: crl.com
  10.  
  11. Markus Heller <Markus.Heller@studbox.uni-stuttgart.de> writes:
  12.  
  13. >I have a global variable :
  14.  
  15. >char *text=NULL;
  16.  
  17. >I want to use it to store different "strings" (at diffreent times).
  18. >E.g., if I want to sore 10 characters in text, I do a 
  19. >text=(char *) malloc(10*sizeof(char));
  20. >When I want to use text to store 3 other characters, I first do a
  21. >free(text); text=NULL; and finally a
  22. >text=(char *) malloc(3*sizeof(char));
  23. >But to my surprise there are still the 4thh to 10th charcter of
  24. >text contained before the free(text)/malloc... ???
  25. >This happens under linux, but why ?
  26.  
  27. I think that a better question would be "why not?" There's nothing in C 
  28. to prevent malloc from returning a pointer to just-freed space if the 
  29. data fits.
  30.  
  31. Since I suspect you're interested in finding a way to determine where the 
  32. newly-stored string ends, perhaps you might want to look at putting in 
  33. some sort of termination character at the end of your string? Such as '\0'?
  34. Either that, or store the number of significant characters in your 'new' 
  35. string. You should not rely on the character at the end of a malloced 
  36. string having any specified value --- and never rely on anything about 
  37. space that is not currently malloced.
  38.  
  39.   Bob
  40.